export const wsConn = function (url, onopen, msgHandler, onclose) {
  const ws = {
    url: url,
  }
  try {
    console.log('wsConn url: ', url)
    const socket = new WebSocket(url)
    socket.onopen = () => {
      ws.socket = socket
      ws.onclose = onclose
      onopen()
    }
    socket.onmessage = msgHandler
    socket.onerror = () => {
    }
    socket.onclose = () => {
      ws.socket = null
    }
  } catch (e) {
    ws.socket = null
    console.log('new WebSocket fail: ', e)
  }
  ws.url = url
  return ws
}

export const wsClose = function (ws) {
  if (ws.socket !== null) {
    ws.onclose !== undefined && ws.onclose !== null && ws.onclose()
    ws.socket.close()
    ws.socket = null
    console.log('wsClose', ws)
  }
}

export const wsReconn = function (ws, onopen, msgHandler, onclose) {
  wsClose(ws)
  console.log('wsReconn: ', ws)
  return wsConn(ws.url, onopen, msgHandler, onclose)
}

export const wsConnecting = function (ws, msg) {
  setTimeout(() => {
    if (ws.socket.readyState === 0) {
      wsConnecting(ws, msg)
      console.log('wsConnecting', ws)
    } else {
      ws.socket.send(JSON.stringify(msg))
    }
  }, 1000)
}

export const wsSend = function (ws, msg) {
  if (ws.socket !== null) {
    if (ws.socket.readyState === 1) {
      const data = JSON.stringify(msg)
      ws.socket.send(data)
    } else if (ws.socket.readyState === 0) {
      wsConnecting(msg)
    } else if (ws.socket.readyState === 3) {
      console.log('ws.socket.readyState: ', ws.socket.readyState)
    }
  } else {
    console.log('wsSend fail, ws.socket == null', ws)
  }
}
